<template>
  <div class="c-bg-sgray c-maxw640">
    <!-- 约课系统的线上线下支付 -->
    <my-small-tabbar v-if="showIsOnline" :tabList="tabList" :tabIndex="isOnline" @changeTab="changeType" class="c-bg-white c-mt20"></my-small-tabbar>
    <div class="c-mt14 c-bd-b1 c-fs28 c-ph24 c-pt28 c-pb20 c-bg-white" v-if="!showIsOnline">
      支付平台
    </div>
    <div class="c-pl24 c-bg-white" v-if="isOnline == 1">
      <div v-if="enableWxCreditPay && isWeiXin" class="c-hh80 c-flex-row c-aligni-center c-pr24" @click="clickPayType(4)">
        <img :src="$addXossFilter(require('@/assets/i/wap/course/wx_pay_credit.png'))" :class="Number(totalPrice)== 0 ? 'pic-gray' : ''" class="c-ww40 c-hh40" alt="">
        <div class="c-w0 c-flex-grow1 ">
          <div :class="Number(totalPrice) > 0 ? 'c-fc-xblack' : 'c-fc-gray'" class="c-fs24 c-lh c-pl20" >微信支付分 | 先学后付</div>
          <div :class="Number(totalPrice) > 0 ? 'c-fc-gray' : 'c-fc-sgray'" class="c-fs20 c-lh c-pl20 c-mt8" >600分及以上可享，上完单节课后自动付款</div>
        </div>
        <div class="c-textAlign-r iconfont c-fs28 c-lh" :class="payType == 4 ? 'theme-fc' : 'c-fc-A'">{{payType == 4 ? '&#xe796;' : '&#xe6f7;'}}</div>
      </div>
      <div v-if="ckFrom != 190 && enableGiftCard" class="c-hh80 c-flex-row c-aligni-center c-pr24" @click="clickPayType(2)">
        <img v-if="!!giftCardPic" :src="$addXossFilter(giftCardPic)" class="c-ww40 c-hh40 c-brp50" :class="Number(totalCoin)== 0 ? 'pic-gray' : ''" alt="">
        <div v-else class="iconfont c-fs40 c-lh" :class="Number(totalCoin) > 0 ? 'c-fc-xsorange' : 'c-fc-gray'">&#xe68e;</div>
        <div class="c-w0 c-flex-grow1 c-fs24 c-lh c-pl20" :class="Number(totalCoin) > 0 ? 'c-fc-xblack' : 'c-fc-gray'">{{giftCardName}}（剩余{{coinBalance}}）</div>
        <div class="c-textAlign-r iconfont c-fs28 c-lh" :class="payType == 2 ? 'theme-fc' : 'c-fc-A'">{{payType == 2 ? '&#xe796;' : '&#xe6f7;'}}</div>
      </div>
      <div class="c-hh80 c-flex-row c-aligni-center c-pr24" @click="clickPayType(0)" v-if="!isiOS && enableWxpay">
        <div class="iconfont c-fs40" :class="Number(totalPrice) > 0 ? 'c-fc-green' : 'c-fc-gray'">&#xe61a;</div>
        <div class="c-w0 c-flex-grow1 c-fs24 c-lh c-pl20" :class="Number(totalPrice) > 0 ? 'c-fc-xblack' : 'c-fc-gray'">微信支付</div>
        <div class="c-textAlign-r iconfont c-fs28 c-lh" :class="payType == 0 && Number(totalPrice) > 0 ? 'theme-fc' : 'c-fc-A'">{{payType == 0 && Number(totalPrice) > 0 ? '&#xe796;' : '&#xe6f7;'}}</div>
      </div>
      <div class="c-hh80 c-flex-row c-aligni-center c-pr24 coms-live-iframe-none" @click="clickPayType(3)" v-if="!isiOS && enableAlipay == 1 && !$isWxApp() && ckFrom != 103 && ckFrom != 104">
        <div class="iconfont c-fs40" :class="Number(totalPrice) > 0 ? 'c-fc-xblue' : 'c-fc-gray'">&#xe74e;</div>
        <div class="c-w0 c-flex-grow1 c-fs24 c-lh c-pl20" :class="Number(totalPrice) > 0 ? 'c-fc-xblack' : 'c-fc-gray'">支付宝支付</div>
        <div class="c-textAlign-r iconfont c-fs28 c-lh" :class="payType == 3 && Number(totalPrice) > 0 ? 'theme-fc' : 'c-fc-gray'">{{payType == 3 && Number(totalPrice) > 0 ? '&#xe796;' : '&#xe6f7;'}}</div>
      </div>
      <div v-if="ckFrom != 103 && ckFrom != 104 && !isFashou" class="c-hh80 c-flex-row c-aligni-center c-pr24" @click="clickPayType(1)">
        <div class="iconfont c-fs40 c-lh" :class="(Number(balance) >= Number(totalPrice)) && (enablePayKnowledge || Number(totalPrice) == 0 || isiOS) ? 'c-fc-sorange' : 'c-fc-gray'">&#xe602;</div>
        <div class="c-w0 c-flex-grow1 c-fs24 c-lh c-pl20" :class="(Number(balance) >= Number(totalPrice)) && (enablePayKnowledge || Number(totalPrice) == 0 || isiOS) ? 'c-fc-xblack' : 'c-fc-gray'">账户余额{{'￥' | iosPriceFilter}}{{Number(balance).toFixed(2)}}</div>
        <div class="c-textAlign-r iconfont c-fs28 c-lh" :class="payType == 1 && (Number(balance) >= Number(totalPrice)) && (enablePayKnowledge || Number(totalPrice) == 0 || isiOS) ? 'theme-fc' : 'c-fc-A'">{{payType == 1 ? '&#xe796;' : '&#xe6f7;'}}</div>
      </div>
    </div>
    <div class="theme-fc c-fs24 c-text-decoration-underline c-ph24 c-pt16" v-if="isiOS" @click="goRecharge">前往充值中心</div>
    <!-- 约课的线下支付了 填写手机号 -->
    <div class="c-bg-white c-ph24" v-if="isOnline == 0">
      <div class="c-fs22 c-lh24 c-fc-sblack c-pt40 c-mb20">若已线下支付，请填写报名时的手机号以完成支付信息核销</div>
      <div class="c-fs26 c-lh26 c-fc-xblack c-w100 c-hh100 c-bd-b1-f6 c-flex-row c-aligni-center">
        <div class="c-flex-shrink0 c-fc-red c-mr4">*</div>
        <div class="c-flex-shrink0 c-mr20">输入手机号</div>
        <input class="c-flex-grow1 c-fs26 c-bd0 c-fc-xblack c-textAlign-r" type="tel" maxlength="11" @focus="inputFocus" @blur="inputBlur" v-model="mobile" placeholder="请输入手机号" />
      </div>
      <div class="c-fs26 c-lh26 c-fc-xblack c-w100 c-hh100 c-bd-b1-f6 c-flex-row c-aligni-center" v-if="companyAuth.enableDeclareModule == 0">
        <div class="c-flex-shrink0 c-fc-red c-mr4">*</div>
        <div class="c-flex-shrink0 c-mr20">图形验证码</div>
        <input class="c-flex-grow1 c-w0 c-fs26 c-bd0 c-fc-xblack c-textAlign-r" type="tel" maxlength="4" v-model="imgCode" placeholder="请输入图形验证码" />
        <img :src="$addXossFilter(codeImgInfo.img)" @click="getImgCode" class="c-flex-shrink0 c-ml20 c-ww130" alt="">
      </div>
      <div class="c-fs26 c-lh26 c-fc-xblack c-w100 c-hh100 c-bd-b1-f6 c-flex-row c-aligni-center" v-if="companyAuth.enableDeclareModule == 0">
        <div class="c-flex-shrink0 c-fc-red c-mr4">*</div>
        <div class="c-flex-shrink0 c-mr20">短信验证码</div>
        <input class="c-flex-grow1 c-w0 c-fs26 c-bd0 c-fc-xblack c-textAlign-r" type="tel" maxlength="4" @input="code=code.slice(0, 4)" v-model="code" placeholder="请输入短信验证码" />
        <div class="c-flex-shrink0 c-ml20" :class="yzText == '发送中' ? 'c-fc-sblack': 'theme-fc '" @click="getYzcode">{{yzText}}</div>
      </div>
    </div>
    <!-- 约课的线下支付 -->
    <div v-if="isOnline == 0" class="c-pf c-p-b0 c-p-l0 c-maxw640 c-bg-white c-hh110 c-w100 c-flex-row c-flex-center c-ph24" >
      <div @click="confirmOffLine" class="c-hh76 c-w100 c-flex-row c-flex-center theme-bg c-fc-white c-fs28 c-br40">确认</div>
    </div>
  </div>

</template>

<script>
import { utilJs } from "@/utils/common.js";
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
let inputScrollTop = 0;
export default {
  name: "PayAndVip",
  components: {
    MySmallTabbar
  },
  props: {
    ckFrom: {
      type: Number,
      default: 0
    },
    balance: {
      type: String,
      default: '0',
    },
    permission: {
      type: Number,
      default: 17,
    },
    totalPrice: {
      type: String,
      default: '0',
    },
    // 约课系统显示线上线下支付tab
    showIsOnline: {
      type: Boolean,
      default: false
    },
    isOnline: {
      type: Number,
      default: 0
    },
    enableGiftCard: { // 是否能用虚拟币支付
      type: Boolean,
      default: false
    },
    coinBalance: { // 虚拟币余额
      type: Number,
      default: 0
    },
    totalCoin: { // 该产品当前需要支付的虚拟币数量
      type: Number,
      default: 0
    },
    enablePayKnowledge: { //是否可以用余额支付知识产品
      type: Boolean,
      default: true
    },
    enableWxpay: { // 是否开启微信支付
      type: Boolean,
      default: true
    },
    enableWxCreditPay: { //
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      enableAlipay: localStorage.getItem("enableAlipay") || 0,
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : 'mb5_default',
      payType: navigator.userAgent.indexOf('IOSLogin') > -1 || navigator.userAgent.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf("IOSNewApp") > -1 ? 1 : 0,
      isiOS: navigator.userAgent.indexOf('IOSLogin') > -1 || navigator.userAgent.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf("IOSNewApp") > -1,
      isOnline: 0, // 是否线上支付
      num: 60,
      interval: null,
      yzText: "获取验证码",
      isYz: true,
      mobile: '', // 线下支付的手机号
      code: '', // 线下支付的验证码 约课的
      // declareOrderId: -1, // 报单的id （约课线下支付）
      isClick: false, // 点击验证码
      isSubmit: false, // 是否点击确定
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      codeImgInfo: '', //图形验证码信息
      imgCode: '', //填入的图形验证码
      tabList: [{
        title: '线上支付',
        index: 1,
      }, {
        title: '我已支付',
        index: 0,
      }],
      giftCardName: '',
      giftCardPic: '',
      cfrom: global.ckFrom,
      isWeiXin: true,
      isFashou: localStorage.getItem('isFaShou') == 1,
    };
  },
  mounted() {
    this.isWeiXin = utilJs.isWeiXin();
    if (this.showIsOnline && this.companyAuth.enableDeclareModule == 0) {
      this.getImgCode();
    }
    this.enableAlipay = this.isFashou ? 0 : (localStorage.getItem("enableAlipay") || 0);
    this.payType = (this.enableGiftCard && this.totalCoin) ? 2 : this.payType;
    utilJs.getGiftCardInfo().then(res => {
      this.giftCardName = res.name || '虚拟币';
      this.giftCardPic = res.coinImg || '';
    })
  },
  watch: {
    totalPrice: function () {
      this.isiOS = navigator.userAgent.indexOf('IOSLogin') > -1 || navigator.userAgent.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf("IOSNewApp") > -1;
      if (this.isiOS) {
        this.payType = 1;
        this.$emit('clickPayType', this.payType);
        return;
      }
      if (Number(this.totalPrice) == 0) { // 价格为0，默认切换为余额支付
        this.payType = 1;
      } else if (Number(this.totalPrice) > 0 && ((this.payType == 1 && (Number(this.totalPrice) > Number(this.balance) || !this.enablePayKnowledge)) || this.payType == -1)) { // 价格大于0 && ((余额支付 && (价格大于余额 || 未开启余额支付虚拟商品) || 未选中支付方式))，根据优先级选中支付方式
        this.payType = this.getDefaultPayType();
      }
      this.$emit('clickPayType', this.payType);
    },
    showIsOnline: {
      handler() {
        // this.isOnline = this.$route.query.ckFrom == 53 ? 0 : 1;
      },
      immediate: true
    }
  },
  computed: {
  },
  methods: {
    getDefaultPayType() {
      let payType = -1;
      // 小程序不支持支付宝支付
      let enableAlipay = !!(localStorage.getItem("enableAlipay") == 1) && !this.$isWxApp();
      // （虚拟币 > 微信支付 > 支付宝支付 > 余额支付）除了价格为0的情况，余额支付优先，其他的情况都遵循这个优先级
      if (this.totalPrice == 0) {
        payType = 1;
      } else if (this.enableGiftCard) {
        payType = 2;
      } else if (this.enableWxpay) {
        payType = 0;
      } else if (enableAlipay) {
        payType = 3;
      } else if (this.enablePayKnowledge == 1 && Number(this.balance || 0) > 0 && Number(this.balance || 0) >= Number(this.totalPrice || 0)) {
        payType = 1;
      }
      console.log(this.payType, 'this.payType')
      return payType;
    },
    changeType: function (type) {
      this.changeOnlinePay(type);
    },
    getImgCode() {
      let $this = this;
      if ($this.isLoading == true) {
        return;
      }
      $this.isLoading = true;
      utilJs.getMethod(`${global.apiurl}common/captcha`, res => {
        $this.codeImgInfo = res;
        $this.isLoading = false;
      }, failRes => {
        $this.isLoading = false;
      });
    },
    goRecharge() {
      this.$routerGo(this, "replace", { path: '/homePage/course/iosRecharge' });
    },
    clickPayType: function (type) {
      if (this.isiOS) {
        this.payType = 1;
        this.$emit('clickPayType', this.payType);
        return;
      }
      if (Number(this.totalPrice) == 0) { // 价格为0，只能余额支付
        this.payType = 1;
      } else if (Number(this.totalPrice) > 0) {
        if (type == 1 && Number(this.totalPrice) > Number(this.balance)) { // 价格大于余额，也不能选余额支付
          return;
        }
        if (type == 1 && !this.enablePayKnowledge) { // 没开启余额支付
          return;
        }
        // 其余情况，有开启，就能选
        this.payType = type;
      }
      this.$emit('clickPayType', this.payType);
    },
    changeOnlinePay(isOnline) {
      // 切换线上支付类型 isOnline 1线上 0线下
      // this.isOnline = isOnline;
      this.$emit('changeOnlinePay', isOnline);
    },
    getYzMethod: function () {
      this.isYz = false;
      this.num -= 1;
      this.yzText = this.num + "秒后重新获取";
      if (this.num == 0) {
        clearInterval(this.interval);
        this.yzText = "获取验证码";
        this.isYz = true;
        this.num = 60;
        this.isClick = false;
      }
    },
    getYzcode: function () {
      if (!this.isClick) {
        this.isClick = true;
        if (this.mobile) {
          if (this.imgCode == '') {
            this.$showCjToast({
              text: "图片验证码不能为空",
              type: "warn",
            });
            this.isClick = false;
          } else {
            let $this = this;
            $this.yzText = "发送中";
            utilJs.postMethod(
              global.apiurl + "reservations/sendCode",
              {
                mobile: this.mobile,
                rtId: this.$route.query.extId,
                captcha: this.imgCode,
                captchaKey: this.codeImgInfo.key,
              },
              res => {
                if (res.errMsg) {
                  this.isClick = false;
                  $this.yzText = "获取验证码";
                  $this.$cjConfirm({
                    message: res.errMsg,
                    confirmButtonText:'去线上支付',
                    cancelButtonText:'我再看看',
                    onConfirm:() => {
                      $this.changeOnlinePay(1);
                    }
                  })
                } else {
                  this.interval = setInterval(this.getYzMethod, 1000);
                }
              },
              function () {
                clearInterval($this.interval);
                $this.yzText = "获取验证码";
                $this.isYz = true;
                $this.num = 60;
                $this.isClick = false;
              }
            );
          }
        } else {
          this.$showCjToast({
            text: "手机号不能为空",
            type: "warn",
          });
          this.isClick = false;
        }
      }
    },
    confirmOffLine() { // 约课的线下支付 确认核销线下
      let $this = this;
      if (!this.mobile) {
        $this.$showCjToast({
          text: "请填写手机号！",
          type: "warn",
        });
        return;
      };
      if (this.companyAuth.enableDeclareModule == 0 && !this.code) {
        $this.$showCjToast({
          text: "请填写验证码！",
          type: "warn",
        });
        return;
      };
      if (this.isSubmit) { // 防止重复点击
        return;
      }
      this.isSubmit = true;
      //** 核销线下支付的订单 */
      utilJs.postMethod(global.apiurl + 'reservations/offLine',
        {
          rtId: this.$route.query.extId,
          mobile: this.mobile, // 线下支付了的手机号
          code: this.code
        },
        function (res) {
          $this.isSubmit = false;
          if (res.orderId) {
            $this.$showCjToast({
              text: "核销成功",
              type: "success",
            }).then(() => {
              if ($this.companyAuth.enableDeclareModule == 0) { // 约课
                // 存缓存 是从订单返回的详情 要弹出有效期
                sessionStorage.setItem($this.$route.query.extId + 'isFromOrderReservation', 1)
                $this.$routerGo($this, "replace", { path: `/activity/activitySuccess?from=1&activityNo=${$this.$route.query.extId}&fromType=sectionInfo` })
              } else {
                $this.$router.go(-1);
              }
            });
          } else {
            $this.$cjConfirm({
              message: res.errMsg,
              confirmButtonText:'去线上支付',
              cancelButtonText:'我再看看',
              onConfirm:() => {
                $this.changeOnlinePay(1);
              }
            })
          }
        },
        function () { // 错误时
          $this.isSubmit = false;
        }
      );
    },
    //IOS微信6.7以上版本会导致输入法收起的时候，键盘没收起，需要手动滚下屏幕
    inputFocus() {
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        inputScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      }
    },
    inputBlur() {
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        setTimeout(() => {
          document.body.scrollTop = inputScrollTop - 1 || 0;
        });
      }
    },
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.salesTag {
  top: -0.3rem;
  border-radius: 0 0.2rem 0 0.2rem;
}
.mt1 {
  margin-top: 1px;
}
.vip-title-bg {
  background-color: rgba(183, 161, 92, 0.2);
  border-radius: 0.25rem 0px 0.5rem 0px;
}
.pic-gray{
  opacity: 0.5;
}
</style>
